package com.example.pattern.flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 适用 共享技术， 有效地支持大量细粒度的对象
 * 享元 模式
 */
public class FlyweightTest {

    public static void main(String[] args) {

        TreeNode treeNode = new TreeNode(1,2, TreeFactory.getTree("石头树", "green", 5));
        TreeNode treeNode2 = new TreeNode(1,2, TreeFactory.getTree("石头树", "green", 5));
        System.out.println(treeNode);
        System.out.println(treeNode2);


    }

}

class TreeFactory{

    private static Map<String,Tree> treeMap = new ConcurrentHashMap<>();

    public static Tree getTree(String name, String color, int high){
        if(treeMap.containsKey(name)){
            return treeMap.get(name);
        }
        Tree tree = new Tree(name, color, high);
        treeMap.put(name, tree);
        return tree;
    }

}

/**
 * 树的位置信息
 */
class TreeNode{
    private int x;
    private int y;
    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }
}

class Tree{
    private final String name;
    private final String color;
    private final int high;

    public Tree(String name, String color, int high) {
        System.out.println("这里创建树");
        this.name = name;
        this.color = color;
        this.high = high;
    }

    @Override
    public String toString() {
        return "Tree{" +
                "name='" + name + '\'' +
                ", clear='" + color + '\'' +
                ", high=" + high +
                '}';
    }
}
